<?php

namespace app\api\controller;

use ba\Random;

use Throwable;
use think\facade\Db;

use think\facade\Config;
use app\common\model\User;
use app\common\model\Order;
use app\common\model\Gift;
use app\common\model\Expense;
use app\common\model\DeviceDevice as Device;
use app\common\model\DeviceEngine as Engine;
use app\common\controller\Frontend;
use EasyWeChat\MiniApp\Application;
use think\facade\Log;
use app\api\model\GiftCode;
use app\common\model\Trade;
use app\common\library\GatewayLib;
class Mpuser extends Frontend{

    protected array $noNeedLogin = ['engine'];
    
    public function info(){
        if($this->request->isPost()){
            $id = $this->auth->id;
            $user = User::find($id)->toArray();
            $user['remoter'] = Db::name('Remoter')->where('mobile',$user['mobile'])->value('id') > 0 ? true : false;
            $this->success('',$user);
        }
    }
    
    public function engine(){
        if($this->request->isPost()){
            $name = $this->request->post('name','');
            if(strpos($name,'HZ') !== false){
                $str = substr($name,2);
                $engine = Random::decode64($str,true);
                $device = Device::with(['place','engine'])->where('ticket',$engine)->find();
                if($device == null){
                    $this->error('');
                }
                $this->success('',$device);
            }else{
                $this->error('');
            }
            
        }
        
    }
    public function verifycode(){
        if($this->request->isPost()){
            $code = $this->request->post('code',0);
            if(empty($code)){
                $this->error('顶顶顶');
            }
            
            Db::startTrans();
            try {
                $giftCode = GiftCode::where('status',1)->where('create_time','between',[time()-300,time()])->find();

                if(empty($giftCode)){
                    throw new \think\Exception('验证码错误');
                }
                $giftCode->status = 2;
                $giftCode->save();
                $gift = Gift::create([
                   'gift_code'=>$giftCode->gift_code,
                   'user_id'=>$this->auth->id,
                   'remote_user'=>$giftCode->user_id,
                ]);
                Trade::create([
                    'user_id'=> $this->auth->id,
                    'trade_type'=>'recharge',
                    'order_id'=> 0,
                    'type'=>1,
                    'balance'=> 10,
                    'remark'=>'洗车券充值:赠送额加10元',
                ]);
                $gift->gift_status = 2;
                $gift->save();
                // 提交事务
                Db::commit();
               $this->success('success');
            } catch (\think\Exception $e) {
                // 回滚事务
               $this->error('throw');
            }
            $this->success('success');
        }    
    }
    
    public function gift(){
        if($this->request->isPost()){
            $map['user_id'] = $this->auth->id;
            $list = Gift::where($map)->order('id desc')->limit(50)->select();
            $this->success('',$list);
        }
    }
    public function expense(){
        if($this->request->isPost()){
            $map['user_id'] = $this->auth->id;
            $list = Expense::withJoin(['device'],'left')->where($map)->order('id desc')->limit(5)->select();
            $this->success('',$list);
        }
    }
    
    public function order(){
        if($this->request->isPost()){
            $map['user_id'] = $this->auth->id;
            $list = Order::withJoin(['product'],'left')->where($map)->order('id desc')->limit(5)->select();
            $this->success('',$list);
        }
    }
    
    public function qcode(){
        if($this->request->isPost()){
            
            $gift = GiftCode::create([
                'user_id'=> $this->auth->id
            ]);
            $this->success('',$gift);
        }
    }
    public function qcodelist(){
        if($this->request->isPost()){
            $status = $this->request->post('status',0);
            $page = $this->request->post('page',1);
            $map['user_id'] = $this->auth->id;
            if($status){
                $map['status'] = $status;
            }
            $list1 = GiftCode::where($map)->order('create_time desc')->paginate(10);
            $list = GiftCode::where($map)->order('create_time desc')->paginate(10);
            $this->success('',$list->items());
        }
    }
    public function engineend(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $engine = Engine::find($data['engine_id']);
            if($engine['is_online'] == 0 ){
                $this->error('设备不在线',null,51);
            }
            $expense = Expense::where('user_id',$this->auth->id)->where('engine_id',$data['engine_id'])->where('finished',0)->order('id,desc')->find();
            GatewayLib::send2Client($engine['engine_name'],[
                'c'=>'78',
                'i'=>$engine['engine_name'],
                'u'=>$expense['id'],
            ]);
            $this->success('',null,200);
        }
    }
    public function enginestart(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $engine = Engine::find($data['engine_id']);
            if($engine['is_online'] == 0 ){
                $this->error('设备不在线',null,51);
            }
            $user = User::find($this->auth->id);
            $prepay = Expense::where('user_id',$this->auth->id)->where('finished',0)->sum('prepay');
            $balance = $user['balance']+$user['balance_zs']-$prepay;
            if($balance > 6){
                $rmb =[];
                if($user['balance_zs']>=10){
                  $expense =  Expense::create([
                        'user_id'=>$this->auth->id,
                        "out_trade_no"=>date('ymd', time()) . mt_rand(1000, 9999) . substr(time(), '3', '8'),
                        "device_id"=>$data['id'],
                        "engine_id"=>$data['engine_id'],
                        "type"=>'gift',
                        "total"=>0,
                        "prepay"=>'10'
                    ]);
                    //发送余额启动机器
                    $rmb = explode('.',(string)$user['balance_zs']);
                }else{
                    $expense =  Expense::create([
                        'user_id'=>$this->auth->id,
                        "out_trade_no"=>date('ymd', time()) . mt_rand(1000, 9999) . substr(time(), '3', '8'),
                        "device_id"=>$data['id'],
                        "engine_id"=>$data['engine_id'],
                        "type"=>'balance',
                        "total"=>0,
                        "prepay"=>'6'
                    ]);
                    //发送余额启动机器
                    $rmb = explode('.',(string)($user['balance']+$user['balance_zs']));
                    
                    //发送余额启动机器
                }
                GatewayLib::send2Client($engine['engine_name'],[
                    'c'=>'72',
                    'i'=>$engine['engine_name'],
                    'u'=>$expense['id'],
                    'y'=>$rmb[0],
                    'j'=>$rmb[1]
                ]);
                $this->success('',null,200);
            }else{
                $this->error('',null,101);//余额不足
            }
            
            
        }
    }
}